package cn.sakura.common.utils;

import io.jsonwebtoken.*;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;

/**
 * jwt工具类
 *
 * @author icatw
 * @date 2022/05/05
 */
@Data
@Component
@ConfigurationProperties(prefix = "icatw.jwt")
public class JwtUtil {

    private long expire;
    private String secret;
    private String header;

    /**
     * 生成令牌
     *
     * @param username 用户名
     * @return {@link String}
     */
    public String generateToken(String username, String userId) {

        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("username", username);
        map.put("userId", userId);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setClaims(map)
                //.setSubject(username)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)// 7天過期，半个小时过期
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 解析jwt
     *
     * @param jwt jwt
     * @return {@link Claims}
     */
    public Claims getClaimByToken(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            if (e instanceof ExpiredJwtException) {
                return ((ExpiredJwtException) e).getClaims();
            }
            return null;
        }
    }

    /**
     * 根据token获取用户id
     *
     * @param token token
     * @return {@link Claims}
     */
    public String getUserIdByToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            return String.valueOf(claims.get("userId"));
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据token获取用户id
     *
     * @param request 请求
     * @return {@link Claims}
     */
    public String getUserIdByRequest(HttpServletRequest request) {
        try {
            String token = request.getHeader(getHeader());
            if (StringUtils.isBlank(token)) {
                return null;
            }
            Claims claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            return String.valueOf(claims.get("userId"));
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * jwt是否过期
     *
     * @param claims 索赔
     * @return boolean
     */
    public boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }

}
